#include "widget.h"
#include "ui_widget.h"

#include <QDebug>
#include <QMessageBox>
#include <QMouseEvent>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QPainter>
#include <qjsonarray.h>
#include <qjsondocument.h>
#include <qjsonobject.h>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setFixedSize(444,913);
    setWindowFlag(Qt::FramelessWindowHint);
    //右键退出
    menuQuit=new QMenu(this);
    QIcon QIcon(QPixmap(":res/close.png"));
    QAction *colseAct = new QAction(QIcon, tr("退出..."), this);
    menuQuit->addAction(colseAct);
    connect(menuQuit,&QMenu::triggered,this,[=](){
        this->close();
    });

    //由QNetworkAccessManager发起get请求
    manager = new QNetworkAccessManager(this);
    strUrl = "http://v1.yiketianqi.com/api?unescape=1&version=v9&appid=39799487&appsecret=7OhLjEbu";
    QUrl urlTianQi(strUrl);
    //指定请求的url地址
    QNetworkRequest res(urlTianQi);
    reply = manager->get(res);
    //QNetworkRequest网络请求后进行数据读取
    connect(manager,&QNetworkAccessManager::finished,this,&Widget::readHttpRply);

    mWeekList<<ui->labelDay0<<ui->labelDay1<<ui->labelDay2
            <<ui->labelDay3<<ui->labelDay4<<ui->labelDay5;
    mDateList<<ui->labelDate0<<ui->labelDate1<<ui->labelDate2<<ui->labelDate3<<ui->labelDate4<<ui->labelDate5;
    mIconList<<ui->labelWeatherIcon04021<<ui->labelWeatherIcon04022<<ui->labelWeatherIcon04023<<ui->labelWeatherIcon04024<<ui->labelWeatherIcon04025<<ui->labelWeatherIcon04026;
    mWeaTypeList<<ui->labelWeatherText04021<<ui->labelWeatherText04022<<ui->labelWeatherText04023<<ui->labelWeatherText04024<<ui->labelWeatherText04025<<ui->labelWeatherText04026;
    mAirqList<<ui->labellaiq0<<ui->labellaiq1<<ui->labellaiq2<<ui->labellaiq3<<ui->labellaiq4<<ui->labellaiq5;
    mFxList<<ui->labelWeatherIcon04021_1<<ui->labelWeatherIcon04021_2<<ui->labelWeatherIcon04021_3<<ui->labelWeatherIcon04021_4<<ui->labelWeatherIcon04021_5<<ui->labelWeatherIcon04021_6
          <<ui->labelWeatherIcon04021_7;
    mFlList<<ui->labelWeatherText04021_1<<ui->labelWeatherText04021_2<<ui->labelWeatherText04021_3<<ui->labelWeatherText04021_4<<ui->labelWeatherText04021_5
          <<ui->labelWeatherText04021_6<<ui->labelWeatherText04021_7;

    //根据keys,设置icon的路径
    mTypeMap.insert("暴雪",":/res/type/BaoXue.png");
    mTypeMap.insert("暴雨",":/res/type/BaoYu. png");
    mTypeMap.insert("暴雨到大暴雨",":/res/type/BaoYuDaoDaBaoYu.png");
    mTypeMap.insert("大暴雨",":/res/type/DaBaoYu.png");
    mTypeMap.insert("大暴雨到特大暴雨",":/res/type/DaBaoYuDaoTeDaBaoYu.png");
    mTypeMap.insert("大到暴雪",":/res/type/DaDaoBaoXue.png");
    mTypeMap.insert("大雪",":/res/type/DaXue.png");
    mTypeMap.insert("大雨",":/res/type/DaYu.png");
    mTypeMap.insert("冻雨",":/res/type/DongYu.png");
    mTypeMap.insert("多云",":/res/type/DuoYun.png");
    mTypeMap.insert("浮沉",":/res/type/FuChen.png");
    mTypeMap.insert("雷阵雨",":/res/type/LeiZhenYu.png");
    mTypeMap.insert("雷阵雨伴有冰雹",":/res/type/LeiZhenYuBanYouBingBao.png");
    mTypeMap.insert("霾",":/res/type/Mai.png");
    mTypeMap.insert("强沙尘暴",":/res/type/QiangShaChenBao.png");
    mTypeMap.insert("晴",":/res/type/Qing.png");
    mTypeMap.insert("沙尘暴",":/res/type/ShaChenBao.png");
    mTypeMap.insert("特大暴雨",":/res/type/TeDaBaoYu.png");
    mTypeMap.insert("undefined",":/res/type/undefined.png");
    mTypeMap.insert("雾",":/res/type/Wu.png");
    mTypeMap.insert("小到中雪",":/res/type/XiaoDaoZhongXue.png");
    mTypeMap.insert("小到中雨",":/res/type/XiaoDaoZhongYu.png");
    mTypeMap.insert("小雪",":/res/type/XiaoXue.png");
    mTypeMap.insert("小雨",":/res/type/XiaoYu.png");
    mTypeMap.insert("雪",":/res/type/Xue.png");
    mTypeMap.insert("扬沙",":/res/type/YangSha.png");
    mTypeMap.insert("阴",":/res/type/Yin.png");
    mTypeMap.insert("雨",":/res/type/Yu.png");
    mTypeMap.insert("雨夹雪",":/res/type/YuJiaXue.png");
    mTypeMap.insert("阵雪",":/res/type/ZhenXue.png");
    mTypeMap.insert("阵雨",":/res/type/ZhenYu.png");
    mTypeMap.insert("中到大雪",":/res/type/ZhongDaoDaXue.png");
    mTypeMap.insert("中到大雨",":/res/type/ZhongDaoDaYu.png");
    mTypeMap.insert("中雪",":/res/type/ZhongXue.png");
    mTypeMap.insert("中雨",":/res/type/ZhongYu.png");

    //注册事件过滤器
    ui->widget0404->installEventFilter(this);
    ui->widget0403->installEventFilter(this);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button()==Qt::RightButton){
        menuQuit-> exec(QCursor::pos());
    }
    //鼠标当前位置(event->globalPos();) 窗口当前位置（pos()）  窗口新位置
    if(event->button()==Qt::LeftButton){
        //mOffset等于鼠标当前位置减去窗口的当前位置
        mOffset=event->globalPos()-this->pos();
    }

}

//处理鼠标左键按下的拖动窗口事件 鼠标左键按下后的移动，导致这个事件被调用，设置窗口的新位置
void Widget::mouseMoveEvent(QMouseEvent *event)
{
    this->move(event->globalPos()-mOffset);
}




void Widget::parseWeatherJsonData(QByteArray rawData)
{
    QJsonDocument jsonObj = QJsonDocument::fromJson(rawData);
    if(!jsonObj.isNull() && jsonObj.isObject()){
        qDebug() <<"parseWeatherJsonData："<< QString::fromUtf8(rawData);
        QJsonObject objRoot = jsonObj.object();
        //解析日期
        QString date = objRoot["date"].toString();
        QString week = objRoot["week"].toString();
        ui->labelCurrentDate->setText(date+"  "+week);
        //解析城市名称
        QString cityName = objRoot["city"].toString();
        ui->labelCity->setText(cityName+"市");
        //解析当前温度
        QString currentTemp = objRoot["tem"].toString();
        ui->labelTemp->setText(currentTemp+"℃");
        ui->labelTempRangle->setText(objRoot["tem2"].toString()+"~"
                +objRoot["tem1"].toString());
        //解析天气类型
        ui->labelWeatherYype->setText(objRoot["wea"].toString());
        ui->labelWeatherIcon->setPixmap(mTypeMap[objRoot["wea"].toString()]);
        //感冒指数
        ui->labelGaimao->setText(objRoot["air_tips"].toString());
        //风向
        ui->labelFXType->setText(objRoot["win"].toString());
        //风力
        ui->labelFXTypeData->setText(objRoot["win_speed"].toString());
        //PM2.5
        ui->labelPMData->setText(objRoot["air_pm25"].toString());
        //湿度
        ui->labelShiduData->setText(objRoot["humidity"].toString());
        //空气质量
        ui->labelAirData->setText(objRoot["air_level"].toString());
    }else {
        qDebug() <<"请求返回的数据为空！";
    }
}

void Widget::parseWeatherJsonDataNew(QByteArray rawData)
{
    QJsonDocument jsondoc=QJsonDocument::fromJson(rawData);
    if(!jsondoc.isNull() && jsondoc.isObject()){
        QJsonObject jsonRoot=jsondoc.object();
        days[0].mCity=jsonRoot["city"].toString();
        days[0].mPm25=jsonRoot["aqi"].toObject()["pm25"].toString();
        if(jsonRoot.contains("data")&& jsonRoot["data"].isArray()){
            QJsonArray  weaArray=jsonRoot["data"].toArray();
            for (int i=0;i<weaArray.size();i+=1) {
                QJsonObject obj= weaArray[i].toObject();
                //qDebug()<<obj["date"].toString()<<obj["wea"].toString();
                days[i].mDate=obj["date"].toString();
                days[i].mWeek=obj["week"].toString();
                days[i].mWeahterType=obj["wea"].toString();
                days[i].mTemp=obj["tem"].toString();
                days[i].mTempLow=obj["tem2"].toString();
                days[i].mTempHigh=obj["tem1"].toString();
                days[i].mFx=obj["win"].toArray()[0].toString();
                days[i].mFl=obj["win_speed"].toString();
                days[i].mAirg=obj["air_level"].toString();
                days[i].mTips=obj["index"].toArray()[3].toObject()["desc"].toString();
                days[i].mHu=obj["humidity"].toString();
            }
        }
    }
    updateUI();

}

void Widget::updateUI()
{
    QPixmap pixmap;
    //解析日期
    ui->labelCurrentDate->setText(days[0].mDate+"  "+days[0].mWeek);
    //解析城市名称
    ui->labelCity->setText(days[0].mCity+"市");
    //解析当前温度
    ui->labelTemp->setText(days[0].mTemp+"℃");
    ui->labelTempRangle->setText(days[0].mTempLow+"℃"+"~"
            +days[0].mTempHigh+"℃");
    //解析天气类型
    ui->labelWeatherYype->setText(days[0].mWeahterType);
    ui->labelWeatherIcon->setPixmap(mTypeMap[days[0].mWeahterType]);
    //感冒指数
    ui->labelGaimao->setText(days[0].mTips);
    //风向
    ui->labelFXType->setText(days[0].mFx);
    //风力
    ui->labelFXTypeData->setText(days[0].mFl);
    //PM2.5
    ui->labelPMData->setText(days[0].mPm25);
    //湿度
    ui->labelShiduData->setText(days[0].mHu);
    //空气质量
    ui->labelAirData->setText(days[0].mAirg);

    for (int i=0;i<6;i+=1) {
        mDateList[i]->setText(days[i].mDate.split("-").at(1)+"/"+days[i].mDate.split("-").at(2));
        mWeekList[i]->setText(days[i].mWeek);
        mWeekList[0]->setText("今天");
        mWeekList[1]->setText("明天");
        mWeekList[2]->setText("后天");

        int index=days[i].mWeahterType.indexOf("转");
        if(index!=-1){
            pixmap=mTypeMap[days[i].mWeahterType.left(index)];
        }else {
            pixmap=mTypeMap[days[i].mWeahterType];
        }
        //设置图片缩放大小和Label大小能匹配
        pixmap= pixmap.scaled(mIconList[i]->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation);
        mIconList[i]->setMaximumHeight(50);
        mIconList[i]->setPixmap(pixmap);
        mWeaTypeList[i]->setText(days[i].mWeahterType);
        //设置空气质量颜色
        QString airQ=days[i].mAirg;
        mAirqList[i]->setText(airQ);
        if(airQ=="优"){
            mAirqList[i]->setStyleSheet("background-color: rgb(150, 213, 32);border-radius: 7px;color: rgb(230, 230, 230);");
        }
        if(airQ=="良"){
            mAirqList[i]->setStyleSheet("background-color: rgb(239, 92, 34);border-radius: 7px;color: rgb(230, 230, 230);");
        }
        if(airQ=="轻度"){
            mAirqList[i]->setStyleSheet("background-color: rgb(255, 199, 199);border-radius: 7px;color: rgb(230, 230, 230);");
        }
        if(airQ=="中度"){
            mAirqList[i]->setStyleSheet("background-color: rgb(255, 17, 17);border-radius: 7px;color: rgb(230, 230, 230);");
        }
        if(airQ=="重度"){
            mAirqList[i]->setStyleSheet("background-color: rgb(153, 0, 0);border-radius: 7px;color: rgb(230, 230, 230);");
        }

        mFxList[i]->setText(days[i].mFx);
        index=days[i].mFl.indexOf("转");
        if(index!=-1){
            mFlList[i]->setText(days[i].mFl.right(index));
        }else {
            mFlList[i]->setText(days[i].mFl);
        }
    }
    update();
}



void Widget::readHttpRply(QNetworkReply *reply)
{

    int resCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if( reply->error() == QNetworkReply::NoError && resCode == 200){
        //大多数服务器返回的字符编码格式是utf-8
        QByteArray data = reply->readAll();
        //parseWeatherJsonData(data);
        parseWeatherJsonDataNew(data);
        //qDebug() << QString::fromUtf8(data);
    }else{
        // QMessageBox::warning(this,"错误","网络请求失败",QMessageBox::Ok);
        QMessageBox mes;
        mes.setWindowTitle("错误");
        mes.setText("网络请求失败");
        mes.setStyleSheet("QPushButton {color:red}");
        mes.setStandardButtons(QMessageBox::Ok);
        mes.exec();
    }
}

void Widget::on_pushButton_clicked()
{
    QString cityNameFromUser = ui->lineEdit->text();
    QString cityCode = cityCodeUtils.getCityCodeFromName(cityNameFromUser);
    if(cityCode != NULL){
        strUrl += "&cityid=" + cityCode;
        qDebug() << strUrl;
        manager->get(QNetworkRequest(QUrl(strUrl)));
    }else{
        QMessageBox mes;
        mes.setWindowTitle("错误");
        mes.setText("请输入正确的城市名");
        mes.setStyleSheet("QPushButton {color:red}");
        mes.setStandardButtons(QMessageBox::Ok);
        mes.exec();
    }
}

bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    if(watched==ui->widget0404&& event->type()==QEvent::Paint){
        drawTempLineHigh();
        //事件被处理返回true
        return true;
    }
    if(watched==ui->widget0403&& event->type()==QEvent::Paint){
        drawTempLineLow();
        //事件被处理返回true
        return true;
    }
    return QWidget::eventFilter(watched,event);
}


void Widget::drawTempLineHigh()
{

    QPainter painter(ui->widget0404);
    painter.setRenderHint(QPainter::Antialiasing,true);
    painter.setBrush(Qt::yellow);
    painter.setPen(Qt::yellow);

    int ave;
    int sum = 0;
    int offSet = 0;
    int middle = ui->widget0404->height()/2;
    for(int i = 0; i < 6; i++){
        sum += days[i].mTempHigh.toInt();
    }
    ave = sum / 6;

    //定义出6个点
    QPoint points[6];
    for(int i = 0; i < 6; i++){
        points[i].setX(mAirqList[i]->x() + mAirqList[i]->width()/2);
        offSet = (days[i].mTempHigh.toInt() - ave)*3;
        points[i].setY(middle - offSet);
        //画出6个点
        painter.drawEllipse(QPoint(points[i]),3,3);
        //画出当天温度
        painter.drawText(points[i].x()-15,points[i].y()-5,days[i].mTempHigh+"°");
    }

    for(int i = 0; i < 5; i++){
         painter.drawLine(points[i],points[i+1]);
    }
}

void Widget::drawTempLineLow()
{
    QPainter painter(ui->widget0403);
    painter.setRenderHint(QPainter::Antialiasing,true);
    painter.setBrush(QColor(70, 192, 203));
    painter.setPen(QColor(70, 192, 203));

    int ave;
    int sum = 0;
    int offSet = 0;
    int middle = ui->widget0403->height()/2;
    for(int i = 0; i < 6; i++){
        sum += days[i].mTempLow.toInt();
    }
    ave = sum / 6;

    //定义出6个点
    QPoint points[6];
    for(int i = 0; i < 6; i++){
        points[i].setX(mAirqList[i]->x() + mAirqList[i]->width()/2);
        offSet = (days[i].mTempLow.toInt() - ave)*3;
        points[i].setY(middle - offSet);
        //画出6个点
        painter.drawEllipse(QPoint(points[i]),3,3);
        //画出当天温度
        painter.drawText(points[i].x()-15,points[i].y()-5,days[i].mTempLow+"°");
    }

    for(int i = 0; i < 5; i++){
         painter.drawLine(points[i],points[i+1]);
    }
}

void Widget::on_lineEdit_returnPressed()
{
    on_pushButton_clicked();
}
